<template>
    <div class="page-wrapper">
        <BreadMenu />
        <div style="height:8%; padding-bottom:var(--mPadding);">
			<div class="flex-btn large" style="margin-right:var(--sPadding);" @click="info = { visible:true, forEdit:false } ">
				<img :src="Icon1" />新建巡检项
			</div>
            <div class="flex-btn large opacity" style="margin-right:var(--sPadding);" @click="handleExport">
				<img :src="Icon2" />导出成Excel
			</div>
            <div class="flex-btn large opacity" style="margin-right:var(--sPadding);" @click=" importVisible = true ">
				<img :src="Icon3" />Excel批量导入
			</div>
		</div>
		<div style="height:88%">
			<TableWrapper :style="{ height:'100%' }" ref="tableRef" :pageInfo="pageInfo"  :hasControls="false" :sourceData="tableData" :column="column" :total="total" @search="handleSearch" />
        </div>
		<!-- 新建巡检项 -->
		<InspectionAddDrawer v-model:info="info" :tplCode="tplCode" :targetId="targetId" :forObj="forObj" @refresh="fetchList"  />
        <!-- 批量导入 -->
        <el-dialog v-model="importVisible" @close="handleClose" >
            <el-form class="myForm" ref="myForm" label-width="120px" :model="form" :rules="rules">
                <el-form-item label="模板下载"><a style="color:#335CFF;" @click="handleClick">点击下载巡检项模板</a></el-form-item>
                <el-form-item label="上传模板文件" prop="file">
                    <CustomUpload ref="uploadRef" text2="excel模板" :allowTypes="allowTypes" :maxSize="5" prop="file" :maxNumber="1" @on-select="handleSelect" />
                </el-form-item>           
            </el-form>
            <template #footer>
                <div style="display:flex; margin-left:120px; gap:var(--mPadding); margin-top:var(--lPadding); ">
                    <div class="flex-btn middle opacity" @click="handleClose">取消</div>
                    <div class="flex-btn middle" @click="handleSubmit">确认</div>
                </div>
            </template>
        </el-dialog>
	</div> 
</template>

<script setup>
    import { ref, reactive, watch, onMounted, computed, h, nextTick, toRaw } from 'vue';
    import { useRoute } from 'vue-router';
    import { getTplInspectionList, getExcelTpl, delInspection, patchImport } from '@/api/tpl.js'; 
    import { getCycleList } from '@/api/cycle.js';
    import { ElMessage, ElPopconfirm, ElInput  } from 'element-plus' 
    import InspectionAddDrawer from './InspectionAddDrawer.vue';
    import TableWrapper from '@/components/TableWrapper/index.vue';
    import ConfirmDel from '@/components/ConfirmDel.vue';
    import CustomUpload from '@/components/CustomUpload.vue';
    import BreadMenu from '@/components/BreadMenu.vue';
    import { createSheet, downloadExcel, createTpl } from '@/utils/excel.js';
    import Icon1 from '@/assets/icon-add.png';
	import Icon2 from '@/assets/icon-export.png';
	import Icon3 from '@/assets/icon-patch.png';

    
    const route = useRoute();
    const tableData = ref([]);
    const totalData = ref([]);
    const tableRef = ref();
    const total = ref(0);
    const pageInfo = reactive({ page:1, pageSize:10 });
    const cycleList = ref([]);
    const tplCode = ref('');
    const targetId = ref('');
    const info = ref({ visible:false, forEdit:false });
    const importVisible = ref(false);
    const forObj = computed(()=>{
        return targetId.value ? true : false;
    })
    const myForm = ref();
    const form = reactive({
        'file':''
    });
    const rules = reactive({
        file:[{ required:true, message:'请上传文件',  trigger:'blur' }],
    });
    const allowTypes = ['xlsx', 'xls'];
    const uploadRef = ref();
    const column = [
        { label:'序号', width:'5%', isIndex:true, hasTpl:true, render:(row, index)=>{
			const val = ( pageInfo.page - 1 ) * pageInfo.pageSize + index + 1;
			return { com:h('div', null, val )};
		}},
        { label:'巡检项名称', width:'14%', prop:'itemName' },
        { label:'标准与要求', width:'17%', prop:'itemNormAndDemand' },
        { label:'检查方法与工具', width:'10%', prop:'checkWayAndTool' },
        { label:'周期', width:'8%', hasTpl:true, render:row=>{ let obj = cycleList.value.filter(i=>i.cycleId === row.cycleId)[0] || {}; return { com:h('span', null, obj.cycleName || '--' ), val:obj.cycleName }} },
        { label:'记录数值0否1是', width:'7%', hasTpl:true, render:row=>{
            return { com:h('div', null, row.needValueRemark === 1 ? '是' : '否' )}
        }},
        { label:'数值名称', width:'7%', prop:'valueName' },
        { label:'数值单位', width:'5%', prop:'valueUnit' },
        { label:'操作', width:'16%', isAction:true, hasTpl:true, render:(row)=>{
            return {
                com:h('div', { class:'action-container' }, [
                    h('div', { onClick:()=>{ info.value = { visible:true, forEdit:true, row } }}, [h('i', { class:'ri-edit-line' }), h('span', null, '编辑')]),
			    	h(ConfirmDel, { info:'确定删除此巡检项吗？', onConfirm:()=>{ handleDelete( forObj.value ? row.itemTargetId :  row.itemId) } } ),
                ])
            } 
        }
        }
    ]; 	
    const handleSearch = (optional)=>{
	    // 调用请求接口
	    fetchList({ ...optional });
	}
   
    const fetchList = (params)=>{
	    // 实际的axios请求;
	    params = params || {};
        params.page = pageInfo.page;
        params.pageSize = pageInfo.pageSize;
        if ( tplCode.value ) {
            params.templateCode = tplCode.value;
        }
        if ( targetId.value ) {
            params.targetId = targetId.value;
        }
	    getTplInspectionList(params, forObj.value)
	    .then(res=>{
	    	if ( res.data.code === 200 ){
	    		tableData.value = res.data.data;
	    		total.value = res.data.total;
	    	}
	    })
	};
    const fetchCycleList = ()=>{
		// 实际的axios请求;
		getCycleList({ page:1, pageSize:999 })
		.then(res=>{
			if ( res.data.code === 200 ){
                cycleList.value = res.data.data;
			}
		})
	};
    const handleDelete = (id)=>{
		delInspection( forObj.value ? { itemTargetId:id } :  { itemId:id }, forObj.value)
		.then(res=>{
			if ( res.data.code === 200 ) {
				ElMessage({
					type:'success',
					message:'删除巡检项成功！' 
				});
				fetchList();
			}
		})
	}
    const handleClick = ()=>{
        createTpl();
    }
    const handleClose = ()=>{
        form.path = '';
        if ( uploadRef.value ) {
            uploadRef.value.clear();
        }
        importVisible.value = false;
    }
    const handleSelect = (name, path)=>{
        form[name] = path;
        // 清空验证状态
        myForm.value.clearValidate();
    }
    const handleSubmit = ()=>{
        myForm.value.validate(valid=>{
            if ( valid ){
                console.log(uploadRef.value.fileList);
                if ( uploadRef.value.fileList && uploadRef.value.fileList.length ) {
                    let file = uploadRef.value.fileList[0].originFile;
                    let params = { file };
                    if ( forObj.value ) {
                        params.targetId = targetId.value;
                    } else {
                        params.templateCode = tplCode.value;
                    }                  
                    patchImport(params)
                    .then(res=>{
                        if ( res.data.code === 200 ) {
                            handleClose();
                            fetchList();
                            ElMessage({
				            	type:'success',
				            	message:'批量导入巡检项成功！' 
				            });
                        }
                    })
                } else {
                    ElMessage.error('请上传文件')
                }
            }
        })
    }
    const handleExport = ()=>{
        if ( tableData.value.length ) {
            downloadExcel([{ raw:createSheet(column, tableData.value)} ], ( forObj.value ? '对象' : '模板') + '巡检项')
           
        } else {
            ElMessage({
                type:'info',
                message:'数据源为空'
            })
        }
    }
    onMounted(()=>{
        const code = route.query.code;
        const id = route.query.id;
        if ( code ) {
            tplCode.value = code;
        }
        if ( id ) {
            targetId.value = id;
        }
        fetchList();
        fetchCycleList();
    })
</script>
